package com.sinba.common.business.service;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import com.sinba.common.business.dao.ISellDAO;
import com.sinba.common.business.dto.BuyGridDTO;
import com.sinba.common.business.dto.BuyQueryDTO;
import com.sinba.common.business.dto.CombinedPriceStatDTO;
import com.sinba.common.business.dto.SellDTO;
import com.sinba.common.business.dto.SellGridDTO;
import com.sinba.common.business.dto.SellQueryDTO;
import com.sinba.common.business.entity.Sell;
import com.sinba.common.dto.PageDTO;
import com.sinba.common.system.dto.TransactionRecordDTO;
import com.sinba.common.system.entity.TransactionRecord;
import com.sinba.common.system.service.ITransactionRecordService;
import com.sinba.common.user.dao.IRegisterUserDAO;
import com.sinba.common.user.entity.RegisterUser;
import com.sinba.common.utils.DoubleFormat;
import com.sinba.common.utils.ToolUtils;
import com.sinba.common.utils.TranType;

public class SellService implements ISellService {

	@Autowired
	private ISellDAO sellDAO;
	@Autowired
	private ITransactionRecordService transactionRecordService;
	@Autowired
	private IBuyService buyService;
	@Autowired
	private IRegisterUserDAO registerUserDAO;
	
	@Transactional
	public synchronized String save(SellDTO dto) {
		// TODO Auto-generated method stub
		
		//股票卖出写法
		RegisterUser registerUser = registerUserDAO.findUniqueBy("loginName", dto.getSellUser());
		Sell entity = new Sell();
		SellDTO.dto2entity(dto, entity);
		entity.setSurplusMoney(dto.getSellMoney());
		entity.setUser(registerUser);
		sellDAO.merge(entity);
		entity.setScode(ToolUtils.d6Format(entity.getId()));
		return "恭喜,得到援助申请成功!";
		
		//援助写法
		/*if(dto!=null && dto.getSellMoney()>0 && dto.getSellUser()!=null){
			//判断账户余额是否够
			Double balance = 0D;
			
			Sell chageDaySell = findLastTimeSell(dto.getSellUser());
			if(chageDaySell != null && judgeIsToDateObject(chageDaySell) ){
				return "申请得到援助失败,每天只允许申请得到援助一次!";
			}
			
			
			
			//如果援助还有未结束不允许挂单
			if(buyService.isNotCompleteOrder(dto.getSellUser())){
				return "申请得到援助失败,全部的得到援助申请结束后才允许申请!";
			}
			
			//全部的援助申请拿足7天的日分红才允许挂单
			if(!isGetFullRiFengHong(dto.getSellUser())){
				return "全部的提供援助申请拿满7天的日利息后才允许继续得到援助申请!";
			}
			
			balance = transactionRecordService.findUserBalance(dto.getSellUser(), TranType.DYNAMIC);
			if(balance>0 && (balance-dto.getSellMoney())>=0){
				RegisterUser registerUser = registerUserDAO.findUniqueBy("loginName", dto.getSellUser());
				Sell entity = new Sell();
				SellDTO.dto2entity(dto, entity);
				entity.setSurplusMoney(dto.getSellMoney());
				entity.setUser(registerUser);
				sellDAO.merge(entity);
				
				
				TransactionRecord tr1 = new TransactionRecord();
				tr1.setLoginName(dto.getSellUser());
				tr1.setTransactionObject("system");
				tr1.setTransactionType(TranType.MaiChu);
				tr1.setRemark("接受援助金额："+dto.getSellMoney());
				transactionRecordService.updateTran(tr1, TranType.DYNAMIC, dto.getSellMoney().doubleValue(), TranType.CUT);
				
				
				
				
				return "恭喜,得到援助申请成功!";
			}else{
				return "申请得到援助失败,账户余额不足!";	
			}
			
		}else{
			return "申请得到援助失败,请重试或联系客服!";
		}*/
		
		
	}
	/**
	 * 是否已拿满7天利息
	 */
	public boolean isGetFullRiFengHong(String loginName){
		//援助申请
		BuyQueryDTO queryDTO = new BuyQueryDTO();
		queryDTO.setBuyUser(loginName);
		queryDTO.setLimit(100);
		queryDTO.setMultipleStatus(new Integer[]{0,1,2});
		PageDTO pageDTO = buyService.findBuyPage(queryDTO,null,null);
		Integer buyQuy = pageDTO.getTotalSize();
		if(buyQuy==0){
			return true;
		}
		List<BuyGridDTO> buyGrids = (List<BuyGridDTO>)pageDTO.getData();
		
		List<String> remarks = new ArrayList<String>();
		for(BuyGridDTO buy : buyGrids){
			remarks.add("日利息("+buy.getId()+")");
//			System.out.println("---------><<"+buy.getId());
		}
		
		//日分红
		TransactionRecordDTO qdto = new TransactionRecordDTO();
		qdto.setLoginName(loginName);
		qdto.setLimit(100);
		qdto.setTransactionType(TranType.RiFenHong);
		qdto.setRemarks(remarks);
		PageDTO pageDTO1 = transactionRecordService.findTransactionRecordPager(qdto, null, null);
		Integer total = pageDTO1.getTotalSize();
//		System.out.println("....................>"+total);
		if(buyQuy*7 <= total){
			return true;
		}else{
			return false;
		}
		
		
	}
	

	@Transactional
	public synchronized String clean(SellDTO dto) {
		Sell entity = sellDAO.findById(dto.getId());
		if(entity != null && entity.getStatus().equals(0)){
			//判断状态（Tan:不需要了）
			/*if(chageTwoTimesInMonth(entity.getSellUser())){
				return "Only canceled twice a month! <br> 一个月内只能取消了两次!";
			}*/

			//更新状态
			entity.setStatus(3);
			sellDAO.merge(entity);
			
			//将卖出的金额退还到对应的账户下
			canelSellAndRollbackMoney(entity);
			return "得到援助取消成功!";
		}else{
			return "得到援助取消失败!";
		}
		
		
	}

	@Transactional
	public PageDTO findSellPage(SellQueryDTO queryDto, String sord, String sidx) {
		// TODO Auto-generated method stub
		PageDTO pageDto = sellDAO.findSellPage(queryDto, sord, sidx);
		List<Sell> lists = pageDto.getData();
		List<SellGridDTO> dtos = new ArrayList<SellGridDTO>();
		for(Sell buy:lists){
			SellGridDTO dto = new SellGridDTO();
			SellGridDTO.entity2dto(buy, dto);
			dtos.add(dto);
		}
		pageDto.setData(dtos);
		return pageDto;
	}
	
	@SuppressWarnings("unchecked")
	@Transactional
	private Sell findLastTimeSell(String sellUser){
		SellQueryDTO queryDto = new SellQueryDTO();
		queryDto.setStart(0);
		queryDto.setLimit(1);
		queryDto.setSellUser(sellUser);
		PageDTO pageDTO = sellDAO.findSellPage(queryDto , "desc", "createTime");
		List<Sell> lists = pageDTO.getData();
		if(lists != null && lists.size() > 0){
			return lists.get(0);
		}else{
			return null;
		}
	}
	
	/**
	 * 取消后将卖出的金额退还到对应的账户下
	 */
	@Transactional
	private void canelSellAndRollbackMoney(Sell sell){
		TransactionRecord t = new TransactionRecord();
		t.setLoginName(sell.getSellUser());
		t.setTransactionObject("system");
		t.setTransactionType(TranType.MaiChuClean);
		t.setRemark("取消卖出："+sell.getSellMoney());
		transactionRecordService.updateTran(t, sell.getSellType(), sell.getSellMoney().doubleValue(), TranType.ADD);
	}
	/**
	 * 判断是否今天创建
	 * @return
	 */
	@Transactional
	private Boolean judgeIsToDateObject(Sell sell){
		Boolean flag = false;
		Boolean sameYear = false;
		Boolean sameMonth = false;
		Boolean sameDay = false;
		//目标时间
		Calendar createTime = Calendar.getInstance();
		createTime.setTime(sell.getCreateTime());
		//当前日期
		Calendar today = Calendar.getInstance();
		today.setTime(new Date());
		
		if(createTime.get(Calendar.YEAR) == today.get(Calendar.YEAR)){
			sameYear = true;
		}
		if(createTime.get(Calendar.MONTH) == today.get(Calendar.MONTH)){
			sameMonth = true;
		}
		if(createTime.get(Calendar.DAY_OF_MONTH) == today.get(Calendar.DAY_OF_MONTH)){
			sameDay = true;
		}
		if(sameYear && sameMonth && sameDay){
			flag = true;
		}
		return flag;
	}
	
	/**
	 * 判断是否在一个月内取消了两次
	 * @return
	 */
	private Boolean chageTwoTimesInMonth(String sellUser){
		Boolean flag = false;
		Boolean sameYear = false;
		Boolean sameMonth = false;
		int count = 0;
		SellQueryDTO queryDto = new SellQueryDTO();
		queryDto.setSellUser(sellUser);
		queryDto.setStart(0);
		queryDto.setLimit(2);
		queryDto.setStatus(3);
		PageDTO pageDTO = sellDAO.findSellPage(queryDto , "desc", "createTime");
		List<Sell> lists = pageDTO.getData();
		if(lists.size() >= 2){
			for(Sell sell : lists){
				//目标时间
				Calendar createTime = Calendar.getInstance();
				createTime.setTime(sell.getCreateTime());
				//当前日期
				Calendar today = Calendar.getInstance();
				today.setTime(new Date());
				
				if(createTime.get(Calendar.YEAR) == today.get(Calendar.YEAR)){
					sameYear = true;
				}
				if(createTime.get(Calendar.MONTH) == today.get(Calendar.MONTH)){
					sameMonth = true;
				}
				if(sameYear && sameMonth){
					count++;
				}
				sameYear = false;
				sameMonth = false;
			}
		}
		if(count >= 2){
			flag = true;
		}
		return flag;
	}
	
	@Transactional
	public void changeOrder(SellDTO sellDto){
		Sell entity = sellDAO.findById(sellDto.getId());
		if("edit".equals(sellDto.getRemark())){
			entity.setSellMoney(sellDto.getSellMoney());
			entity.setSurplusMoney(sellDto.getSellMoney());
			entity.setSellPrice(sellDto.getSellPrice());
		}else{
			entity.setPriority(sellDto.getPriority());
			entity.setCreateTime(sellDto.getCreateDate());
		}
		sellDAO.merge(entity);
	}
	
	@Transactional
	public Sell findTop1SellOrder(){
		return sellDAO.findTop1SellOrder();
	}
	
	/**
	 * 卖出价格小于0.2并且未交易结束的所有股数
	 * @return 
	 */
	@Transactional
	public Map<String,Double> lt2AllSell(){
		Double result1 = 0D;
		Double result2 = 0D;
		try {
			List<Object[]> objs = sellDAO.lt2AllSell();
			for(Object[] obj : objs){
				Long temp = (Long)obj[0];
				if(temp!=null)
					result1 = temp.doubleValue();
				result2 = (Double)obj[1];
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		if(result1==null){
			result1 = 0D;
		}
		if(result2==null){
			result2 = 0D;
		}
		Map<String,Double> maps = new HashMap<String, Double>();
		maps.put("lt2AllSell1", result1);
		maps.put("lt2AllSell2", result2);
		return maps;
	}
	
	@Transactional
	public List<CombinedPriceStatDTO> combinedPriceStat(){
		Long result1 = 0L;
		Long result2 = 0L;
		List<CombinedPriceStatDTO> results = new ArrayList<CombinedPriceStatDTO>();
		try {
			List<Object[]> objs = sellDAO.combinedPriceStat();
			for(Object[] obj : objs){
				CombinedPriceStatDTO dto = new CombinedPriceStatDTO();
				dto.setSellPrice((Double)obj[0]);
				dto.setSurplusMoney((Long)obj[1]);
				results.add(dto);
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		
		return results;
	}
	
}
